import os, argparse, ConfigParser, swmmr

def setConfig(**kwargs):
    parser = ConfigParser.SafeConfigParser()
    usercfg_path = os.path.join(os.path.expanduser('~'), '_swmmr')
    if not os.path.exists(usercfg_path):
        with open(usercfg_path, 'w') as f:
            f.write('[main]')
    parser.read(usercfg_path)
    for key, value in kwargs.items():
        if isinstance(value, str):
            value = '"' + value + '"'
        parser.set('main', key, str(value))

    with open(usercfg_path, 'w') as f:
        parser.write(f)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--test", action='store_true')
    parser.add_argument("--install", action='store_true')
    parser.add_argument("-u", type=str)
    parser.add_argument("-p", type=str)
    parser.add_argument("-s", type=str)
    args = parser.parse_args()
    if args.test:
        try:
            swmmr.handle(server = args.s, login = args.u, password = args.p)
        except:
            setConfig(server = None, login = None, password = None, autoconnect = False)
            raise
        else:
            setConfig(server = args.s, login = args.u, password = args.p, autoconnect = True)
    if args.install:
        swmmr.build(server = args.s, admin_login = args.u, admin_password = args.p)
        setConfig(build_server = args.s, admin_login = args.u)

